/*******************************************
 * Copyright 2007 Aphrodite Framework for javaME .
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Public License v2.0
 * which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
 * Email : owner@aphroditeme.dev.java.net
 * Contributors:
 *     Kent Elton - initial API and implementation
 *******************************************/

package com.aphrodite.blackberry.util;

import net.rim.blackberry.api.mail.Address;
import net.rim.blackberry.api.mail.AddressException;
import net.rim.blackberry.api.mail.Folder;
import net.rim.blackberry.api.mail.Message;
import net.rim.blackberry.api.mail.MessagingException;
import net.rim.blackberry.api.mail.ServiceConfiguration;
import net.rim.blackberry.api.mail.Session;
import net.rim.blackberry.api.mail.Store;
import net.rim.blackberry.api.mail.Transport;

class EmailEngine {
	/**
	 * Get the email address of the blackberry device
	 * 
	 * @return String
	 */
	public String getDeviceEmail() {
		String emailAddress = new String();
		Session session = Session.getDefaultInstance();
		if (session != null) {
			// now the store
			Store store = session.getStore();
			// then the service configuration
			ServiceConfiguration serviceConfig = store.getServiceConfiguration();
			// now get the email address
			emailAddress = serviceConfig.getEmailAddress();

		}
		return emailAddress;
	}

	public void sendEmail(final String to, final String rcvName, final String subject, final String body) {

		new Thread() {
			public void run() {
				Store store = Session.getDefaultInstance().getStore();
				Folder[] folders = store.list(Folder.SENT);
				Folder sentfolder = folders[0];
				Message msg = new Message(sentfolder);

				// Add TO Recipients.
				Address toList[] = new Address[1];

				try {

					toList[0] = new Address(to, rcvName);
				} catch (AddressException e) {
					System.out.println(e.toString());
				}
				try {
					msg.addRecipients(Message.RecipientType.TO, toList);
				} catch (MessagingException e) {
					System.out.println(e.toString());

				}
				// Add the subject.
				msg.setSubject(subject);
				// Add the message body.
				try {

					msg.setContent(body);
				} catch (MessagingException e) {
					// Handle messaging exceptions.
					System.out.println(e.getMessage());
				}
				// Send the message.
				try {
					Transport.send(msg);

				} catch (MessagingException e) {
					System.out.println(e.getMessage());
				}

				System.out.println("Email sent successfully.");
			}
		}.start();
	}

}
